package com.example.chat.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.chat.service.UserService;
import com.example.chat.pojo.vo.MessageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.example.chat.constants.RedisConstants.NEW_MESSAGE_KEY;

/**
 * WebSocket消息服务类
 */
@Slf4j
@Component
@ServerEndpoint("/ws/message/{id}")
public class WebSocketMessageServer {

    /**与某个客户端的连接会话，需要通过它来给客户端发送数据,
     * 也可以通过session().close();主动关闭连接
     * */
    private Session session;

    /**
     * 业务标识
     */
    private String id;

    /**
     * 一个Map,其实就是一个容器
     */
    public static Map<String, WebSocketMessageServer> socketServerMap = new ConcurrentHashMap<>();

    private static UserService userService;

    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }

    private static StringRedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        if (StrUtil.isNotEmpty(id)){
            boolean checked = userService.checkUser(id);
            if (checked){
                log.info("message连接成功：" + id);
                this.session = session;
                this.id = id;
                socketServerMap.put(id,this);
            }
        }
    }

    /**
     * 连接关闭,调用的方法
     */
    @OnClose
    public void onClose() {
        if (StrUtil.isNotEmpty(this.id)){
            socketServerMap.remove(this.id);
            log.info("message连接关闭：" + id);
        }
    }

    /**
     * 错误回调
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error(error.toString());
    }

    /**
     * 接收前端推送的消息
     */
    @OnMessage
    public void onMessage(Session session, String msg) {
        log.info("接受到的消息：" + msg);
    }

    /**
     * 服务器主动推送消息
     */
    public void sendMessage(MessageVO message) {
        try {
            WebSocketMessageServer webSocketMessageServerToUser = socketServerMap.get(message.getToUserId());
            WebSocketMessageServer webSocketMessageServerFormUser = socketServerMap.get(message.getFormUserId());
            if (webSocketMessageServerFormUser != null) {//推送自己的消息
                log.info("message开始发送自己");
                webSocketMessageServerFormUser.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message)); // 给前端发送消息！
                log.info("message发送自己成功");
            }
            if (webSocketMessageServerToUser != null) {//对方在线，进行实时推送
                log.info("message开始发送对方");
                webSocketMessageServerToUser.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message)); // 给前端发送消息！
                log.info("message发送对方成功");
            }else {//对方不在线，进行新消息更新
                int count = 0;
                String json = redisTemplate.opsForValue().get(NEW_MESSAGE_KEY + message.getFormUserId() + message.getToUserId());
                if (StrUtil.isNotEmpty(json)){
                    count = Integer.valueOf(json);
                }
                redisTemplate.opsForValue().set(NEW_MESSAGE_KEY + message.getFormUserId() + message.getToUserId(),String.valueOf(++count));
            }
        } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

